package com.ch.gulimall.product.exception;

import com.ch.common.exception.BizCodeEnum;
import com.ch.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * basePackages代表处理是哪个包下的异常处理
 * 集中处理
 */
@Slf4j
@ControllerAdvice(basePackages = "com.ch.gulimall.product.controller")
public class GulimallExceptionAdvise {
    @ResponseBody
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handValidException(MethodArgumentNotValidException e) {
        BindingResult result = e.getBindingResult();
        //获取校验的规则提示
        Map<String, String> map = new ConcurrentHashMap<>();
        result.getFieldErrors().forEach(fieldError -> {
            //获取错误信息
            String defaultMessage = fieldError.getDefaultMessage();
            //获取属性的名字
            String field = fieldError.getField();
            map.put(field, defaultMessage);
        });
        return R.error(BizCodeEnum.VAILD_EXCEPTION.getCode(), "提交的数据不合法,").put("data", map);
    }

    @ExceptionHandler(value = Throwable.class)
    public R handleException(Throwable throwable) {
        return R.error(BizCodeEnum.UNKNOW_EXCEPTION.getCode(), BizCodeEnum.UNKNOW_EXCEPTION.getMessage());
    }

}
